package com.xiaoxiang.auth.service;

import com.xiaoxiang.auth.config.PermissionCache;
import com.xiaoxiang.auth.dto.RolePermissionDo;
import com.xiaoxiang.auth.entity.Permission;
import com.xiaoxiang.auth.util.JwtUtil;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 基础认证抽象服务
 * @author: haha
 * @date: 2022/3/13 20:03
 */
public abstract class BaseAuthService implements AuthService {

    @Resource
    protected UserService userService;

    @Resource
    protected RoleService roleService;

    @Resource
    protected PermissionCache permissionCache;

    @Override
    public boolean verify(String token, String path) {
        if (!JwtUtil.isValid(token) || JwtUtil.isExpiration(token)) {
            return false;
        }
        List<RolePermissionDo> rolePermissionDoList = permissionCache.getCache();
        List roleList = JwtUtil.getRoleName(token);
        Set<String> patternSet = new HashSet<>();
        rolePermissionDoList.forEach((v) -> {
            if (roleList.contains(v.getRoleName())) {
                patternSet.addAll(v.getPermissionList().stream().map(Permission::getPattern).collect(Collectors.toList()));
            }
        });
        PathMatcher pathMatcher = new AntPathMatcher();
        for (String pattern : patternSet) {
            if (pathMatcher.match(pattern, path)) {
                return true;
            }
        }
        return false;
    }
}
